﻿/*************************************************** PAGE FUNCTIONS ***************************************************/
function doReload() {
    location.reload();
}

function TestPayPal() {
    var code = 'code1';
    var description = 'description1';
    var quantity = 1;
    var value = 100;
    var tax = 10;
    $("#myPayPalCart").PayPalCart('add', code, description, quantity, value, tax);
}

function doUpdateReservationModel(model) {
    model.ParkingId = $("#ddlParking").val();
    model.ParkingZoneId = $("#ddlParkingZone").val();
    model.Date = $("#tboxDate").val();
    model.StartHour = $("#ddlStartHour").val();
    model.EndHour = $("#ddlEndHour").val();
    model.CarPlate = $("#tboxCarPlate").val();
    return model;
}

function doReserve(model, url) {
    model = doUpdateReservationModel(model);
    var isValid = doValidateReservation(model);
    if (isValid == true) {
        doAjaxCall(url, model, function (data) { doProcessReservations(data); });
    }
    else {
        doShowError(isValid);
    }
}

function doMobileReserve(model, url, url2) {
    model = doUpdateReservationModel(model);
    var isValid = doValidateReservation(model);
    if (isValid == true) {
        doAjaxCall(url, model, function (data) { doMobileProcessReservations(data, url2); });
    }
    else {
        doShowError(isValid);
    }
}

function doDelete(url, id) {
    //doAjaxCall(url, null, function (data) { doProcessReservations(data); });
    doAjaxSyncPost(url, id, function (data) { doProcessReservations(data); });
}

function doValidateReservation(model) {
    if (model.ParkingID == 0)
        return "El campo Parqueo es requerido.";
    else if (model.ParkingZoneID == 0)
        return "El campo Zona de Parqueo es requerido.";
    else if (model.Date == 0)
        return "El campo Fecha es requerido.";
    else if (model.StartHour == 0)
        return "El campo Entrada es requerido.";
    else if (model.EndHour == 0)
        return "El campo Salida es requerido.";
    else if (model.CarPlate == 0)
        return "El campo Placa es requerido.";
    else
        return true;
}

function doPostPayPal(url) {
    doAjaxCall(url, null, null);
}

function AddPayPal() {
    var code = $("#tboxCode").val();
    var description = $("#tboxDescription").val();
    var quantity = $("#tboxQty").val();
    var value = $("#tboxValue").val();
    var tax = $("#tboxTax").val();
    $("#myPayPalCart").PayPalCart('add', code, description, quantity, value, tax);
}

function doAddPayPalCart(id, reservation, clear) {
    var code = id;
    var description = reservation.ParkingName + " " + reservation.ParkingZoneName + " " + reservation.Date + " " + reservation.StartHour + " " + reservation.EndHour + " Placa: " + reservation.CarPlate;
    var quantity = 1;
    var value = (parseInt(reservation.Amount) + parseInt(reservation.Comission)) / 500;
    var tax = 0;
    $("#myPayPalCart").PayPalCart('add', code, description, quantity, value, tax, clear);
}

function doDeletePayPalCart(id) {
    $("#myPayPalCart").PayPalCart('remove', id);
}

function doUpdatePayPalCart(reservations) {
    var clear = true;
    if (reservations.length > 0) {
        for (var i = 0; i < reservations.length; i++) {
            doAddPayPalCart(i + 1, reservations[i], clear);
            clear = false;
        }
    } else {
        doDeletePayPalCart(1);
    }
}

function doProcessReservations(data) {
    if (data.HasError) {
        doShowError(data.ErrorMessage);
    }
    else {
        //doUpdatePayPalCart(data.Reservations);
        $("#reservationsCart").html(data.ReservationsHtml);
    }
}

function doMobileProcessReservations(data, url) {
    if (data.HasError) {
        doShowError(data.ErrorMessage);
    }
    else {
        window.location = url;
    }
}

function doSelectParking(model, url) {
    model = doUpdateReservationModel(model);
    if (model.ParkingId == "0")
        return;
    doAjaxCall(url, model, function (data) { doFillSelect("#ddlParkingZone", data.ParkingZones); });
}

function doSelectParkingZone(model, url) {
    model = doUpdateReservationModel(model);
    if (model.ParkingZoneId == "0")
        return;
    doAjaxCall(url, model, function (data) { doFillSelect("#ddlStartHour", data.OpenHours); doUpdatePriceHourAndComission(data.PriceHour, data.Commission); });
}

function doSelectStartHour(model, url) {
    model = doUpdateReservationModel(model);
    if (model.StartHour == "0")
        return;
    doAjaxCall(url, model, function (data) { doFillSelect("#ddlEndHour", data.CloseHours); });
}
function doUpdatePriceHourAndComission(priceHour, commission) {
    var ctrl = $("#lbPriceHourAndComission");
    if (priceHour > 0 && commission > 0) {
        if (ctrl.text() != "") {
            ctrl.text(ctrl.text().replace("[$PHXXX]", "¢" + priceHour).replace("[$CXXX]", "¢" + commission));
        } else {
            ctrl.val(ctrl.val().replace("[$PHXXX]", "¢" + priceHour).replace("[$CXXX]", "¢" + commission));
        }
        ctrl.css('visibility', 'visible');
    }
    else {
        ctrl.css('visibility','hidden');
    }
}

/*************************************************** Parkings View ******************************************************/

function doUpdateCustomerModel(model) {
    model.Customer.Name = $("#tbxCustomerName").val();
    model.Customer.Email = $("#tbxCustomerEmail").val();
    model.Customer.Phone = $("#tbxCustomerPhone").val();
    model.Customer.Address = $("#tbxCustomerAddress").val();
    return model;
}

function doSaveCustomer(model, url) {
    model = doUpdateCustomerModel(model);
    var isValid = doValidateCustomer(model);
    if (isValid == true) {
        doAjaxCall(url, model, function (data) { confirmSaving(data); });
    }
    else {
        doShowError(isValid);
    }
}

function doCreateCustomer(model, url) {
    model = doUpdateCustomerModel(model);
    doAjaxCall(url, model, function (data) { confirmCustomerCreation(data) });
}

function doValidateCustomer(model) {
    if (model.Customer.Name == 0)
        return "El campo Nombre es requerido.";
    else if (model.Customer.Email == 0)
        return "El campo Email es requerido.";
    else if (model.Customer.Phone == 0)
        return "El campo Teléfono es requerido.";
    else if (model.Customer.Address == 0)
        return "El campo Dirección es requerido.";
    else
        return true;
}

function confirmCustomerCreation(data) {
    if (data == true) {
        doShowMessage('Creación Exitosa');
    }
    else {
        doShowError("Por favor intente de nuevo más tarde.");
    }
}

function confirmSaving(data) {
    if (data == true) {
        doShowMessage('Actualización Exitosa');
    }
    else {
        doShowError("Por favor intente de nuevo más tarde.");
    }
}

/*************************************************** CLIENTS ***************************************************/

function removeClient(model, url, customerId) {
    var customer = null;
    for (var i = 0; i < model.Customers.length; i++) {
        if (model.Customers[i].CustomerID == customerId) {
            customer = model.Customers[i];
        }
    }
    var result = false;    
    if (customer != null) {
        doAjaxSyncPost(url, customer, function () { result = true; });
    }
    return result;
}

/*************************************************** GLOBAL FUNCTIONS ***************************************************/
function doAjaxCall(url, vm, successCall) {
    $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: JSON.stringify({ 'model': vm }),
        contentType: 'application/json; charset=utf-8',
        beforeSend: function () { doShowPageLoadingMsg(); },
        complete: function () { doHidePageLoadingMsg(); },
        success: successCall,
        error: function () { alert("AJAX call error"); }
    });
    return false;
}

function doAjaxSyncPost(url, data, successCall) {
    $.ajax({
        async: false,
        url: url,
        type: "POST",
        data: data,
        beforeSend: function () { doShowPageLoadingMsg(); },
        complete: function () { doHidePageLoadingMsg(); },
        success: successCall,
        error: function () { alert("AJAX call error"); }
    });
    return false;
}

function doAjaxRefreshPartialView(url, vm, successCall) {
    $.ajax({
        url: url,
        type: "POST",
        dataType: "html",
        data: JSON.stringify({ 'model': vm }),
        contentType: 'application/json; charset=utf-8',
        beforeSend: function () { doShowPageLoadingMsg(); },
        complete: function () { doHidePageLoadingMsg(); },
        success: successCall,
        error: function () { return false; }
    });
    return false;
}

function doShowPageLoadingMsg() {
    if (usingJQMobile()) {
        $.mobile.showPageLoadingMsg();
    }
    else {
        $.blockUI({ message: '<div><br/><img src="../content/images/loading-bars.gif" /><br/><br/></div>' });
    }
}

function doHidePageLoadingMsg() {
    if (usingJQMobile()) {
        $.mobile.hidePageLoadingMsg();
    }
    else {        
        $(document).ajaxStop($.unblockUI);
    }
}

function usingJQMobile() {
    try {
        $.mobile.hidePageLoadingMsg();
        return true;
    }        
    catch (ex) {
        return false;
    }
}

function doFillSelect(id, data) {
    var html = '';
    var len = data.length;
    $(id).empty();
    $.each(data, function (i, item) {
        html = '<option value="' + item.Value + '">' + item.Text + '</option>';
        $(id).append(html);
    });
    try { $(id).selectmenu("refresh"); } catch (ex) { }
    //$(id).selectmenu("open");
    doTab();
}

function doTab() {
    var e = $.Event('keydown');

    e.which = 9; // TAB
    $(':focus').trigger(e);
}

function doShowError(msg) {
    if (usingJQMobile()) {
        $('<div>').simpledialog2({
            mode: 'button',
            showModal: true,
            headerText: 'Error',
            headerClose: false,
            buttonPrompt: msg,
            buttons: {
                'Cerrar': {
                    click: function() {
                        return true;
                    },
                    icon: null
                }
            }
        });
    }
    else {
        $('<div>' + msg + '</div>').dialog({
            modal: true,
            title: 'Error',
            height: 150,
            width: 350,
            resizable: false,
            draggable: false,
            buttons: {
                Cerrar: function () {
                    $(this).dialog("close");
                }
            },
        });
    }
}

function doShowMessage(msg) {
    $('<div>').simpledialog2({
        mode: 'button',
        showModal: true,
        headerText: 'Información',
        headerClose: false,
        buttonPrompt: msg,
        buttons: {
            'Cerrar': {
                click: function() {
                    return true;
                },
                icon: null
            }
        }
    });
}